package com.wqnmdb.im.netty.data;

import com.alibaba.fastjson.JSON;
import com.wqnmdb.im.domain.contants.ConstantEnum;
import com.wqnmdb.im.domain.mongo.ImApp;
import com.wqnmdb.im.service.mongo.MongoService;
import com.wqnmdb.im.service.redis.RedisStringService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class InitNettyData extends NettyData {

    @Autowired
    private MongoService mongoService;

    @Autowired
    private RedisStringService redisStringService;

    /**
     * 初始化缓存及通道容器
     */
    @PostConstruct
    public void init() {
        redisStringService.delKeyByPrefix(ConstantEnum.REDIS_CACHE_KEYS.getContent() + "*");

        List<ImApp> imApps = mongoService.find(new Query(Criteria.where("status").is(1)), ImApp.class);
        for (ImApp app : imApps) {
            ConcurrentHashMap<ChannelId, ChannelHandlerContext> userHandlerContexts = new ConcurrentHashMap();
            ConcurrentHashMap<String, ChannelId> userChannels = new ConcurrentHashMap();
            SYS_CONTEXT_CHANNEL.put(app.getName(), userHandlerContexts);
            APP_BINDING_CHANNEL.put(app.getName(), userChannels);
        }
        log.info("初始化通道容器(1)完成，当前数量：{}.", SYS_CONTEXT_CHANNEL.size());
        log.info("初始化通道容器(2)完成，当前数量：{}.", APP_BINDING_CHANNEL.size());
    }

    /**
     * 创建容器
     */
    public void createChannelContainer(String appName){
        if (APP_BINDING_CHANNEL.get(appName) == null || SYS_CONTEXT_CHANNEL.get(appName) == null){
            ConcurrentHashMap<ChannelId, ChannelHandlerContext> userHandlerContexts = new ConcurrentHashMap();
            ConcurrentHashMap<String, ChannelId> userChannels = new ConcurrentHashMap();
            SYS_CONTEXT_CHANNEL.put(appName, userHandlerContexts);
            APP_BINDING_CHANNEL.put(appName, userChannels);
            log.info("创建容器(1)成功，当前容器数量：{}.当前有效APP通道：{}.", SYS_CONTEXT_CHANNEL.size(), JSON.toJSONString(SYS_CONTEXT_CHANNEL.keys()));
            log.info("创建容器(2)成功，当前容器数量：{}.当前有效APP通道：{}.", APP_BINDING_CHANNEL.size(), JSON.toJSONString(APP_BINDING_CHANNEL.keys()));
        }
    }
}
